package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.Service.MemberService;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class MemberController {

    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map){
        //校验输入的号码和验证码是否与发送短信的号码和验证码一致
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String tele = jedisPool.getResource().get(telephone + "login");
        if(telephone != null && validateCode != null && code != null && tele != null &&
        telephone.equals(tele) && validateCode.equals(code)){
            //校验成功
            //1.判断该号码是否已注册会员，是则直接跳转首页
            Member member = memberService.findByTelephone(telephone);
           // Member member1 = new Member();
            if(member == null){
                //2.非会员则先自动注册，
                member = new Member();
                member.setPhoneNumber(tele);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //会员则执行下面操作
            //向客户端游览器传回cookie ，内容为手机号
            Cookie cookie = new Cookie("lmp",tele);
            cookie.setMaxAge(60*24*30);
            cookie.setPath("/");//所有路径
            response.addCookie(cookie);
            //同时将会员信息记录到Redis
            String m = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(tele+"member",60*30,m);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }
        return new Result(false,MessageConstant.LOGIN_FAIL);
    }
}
